#include<iostream>
#include<sstream>
#include<string>
#include<cstring>
#include<unistd.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<json/json.h>

using namespace std;

int main(int argc, char* argv[])
{
    int sock, cfd, ret;
    sockaddr_in serv;
    char buf[BUFSIZ];

    bzero(&serv, sizeof(serv));
    serv.sin_family = AF_INET;
    serv.sin_port = htons(8821);
    serv.sin_addr.s_addr = inet_addr("127.0.0.1");

    sock = socket(AF_INET, SOCK_STREAM, 0);

    cfd = connect(sock, (sockaddr*)&serv, sizeof(sockaddr));

    ret = recv(cfd, buf, BUFSIZ, 0);

    write(STDOUT_FILENO, buf, strlen(buf));

    while (1)
    {
        bzero(buf, BUFSIZ);
        read(0, buf, sizeof(buf));
        send(cfd, buf, strlen(buf)-1, 0);

        bzero(buf, sizeof(buf));
        recv(sock, buf, sizeof(buf), 0);

        Json::Value files;
        Json::Reader reader;

        if(reader.parse(buf, files))
        {
            for(unsigned int i = 0; i < files["file"].size(); i++)
            {
                string title = files["file"][i]["title"].asString();
                string summary = files["file"][i]["summary"].asString();
                string url = files["file"][i]["url"].asString();

                stringstream ss;
                ss << "Page: " << title << endl
                    << "Description: " << summary << endl
                    << "Link: " << url << endl;
                
                cout << ss.str() << endl;
                cout << "------------------------" << endl;
            }
        }

    }
    
    close(sock);
    return 0;
}